angular.module('mvcRestBaseApp')
    .factory('User', ['$http',
        function ($http) {
            var configPromisesInWechat = {};
            var isInWeixin = isWeiXin();
            var model = {
                getUserInfoWithCache: _.memoize(function(id) {
                    return new Promise(function(resolve, reject) {
                        $http.get('/wechatshop/user/info/' + id)
                            .success(ngPromiseHandler(resolve, reject))
                            .error(reject);
                    });
                }),
                currentUserInfo: function() {
                    return new Promise(function(resolve, reject) {
                        $http.get('/wechatshop/profile')
                            .success(ngPromiseHandler(resolve, reject))
                            .error(reject);
                    });
                },
                getWechatLoginUrl: function () {
                    return new Promise(function (resolve, reject) {
                        $http.get('/wechatshop/get_wechat_oauth_page_url')
                            .success(ngPromiseHandler(resolve, reject))
                            .error(reject);
                    });
                },
                login: function (username, password, captcha) {
                    return new Promise(function(resolve, reject) {
                        $http({
                            url: '/wechatshop/login',
                            method: 'POST',
                            headers: formHeaders,
                            data: $.param({
                                username: username,
                                password: password,
                                captcha: captcha
                            })
                        }).success(function(data) {
                            if(data.code === 0) {
                                _.extend(WebApp.currentUser, data.data);
                                resolve(data.data);
                            } else {
                                reject(data.data);
                            }
                        }).error(reject);
                    });
                },
                register: function (username, password, isShopOwner) {
                    isShopOwner = isShopOwner ? true : false;
                    return new Promise(function(resolve, reject) {
                        $http({
                            url: '/wechatshop/register',
                            method: 'POST',
                            headers: formHeaders,
                            data: $.param({
                                username: username,
                                password: password,
                                isShopOwner: isShopOwner
                            })
                        }).success(ngPromiseHandler(resolve, reject)).error(reject);
                    });
                },
                createUser: function (username, password, isShopOwner) {
                    isShopOwner = isShopOwner ? true : false;
                    return new Promise(function (resolve, reject) {
                        $http({
                            url: '/wechatshop/user/create',
                            method: 'POST',
                            headers: formHeaders,
                            data: $.param({
                                username: username,
                                password: password,
                                isShopOwner: isShopOwner
                            })
                        }).success(ngPromiseHandler(resolve, reject)).error(reject);
                    });
                },
                getRolesOfUser: function (userId) {
                    return new Promise(function (resolve, reject) {
                        $http.get('/wechatshop/role/user_roles/' + userId)
                            .success(ngPromiseHandler(resolve, reject))
                            .error(reject);
                    });
                },
                addRoleToUser: function (userId, roleId) {
                    return new Promise(function (resolve, reject) {
                        $http({
                            url: '/wechatshop/role/add_user_role',
                            method: 'POST',
                            headers: formHeaders,
                            data: $.param({
                                userId: userId,
                                roleId: roleId
                            })
                        }).success(ngPromiseHandler(resolve, reject))
                            .error(reject);
                    });
                },
                removeRoleFromUser: function (userId, roleId) {
                    return new Promise(function (resolve, reject) {
                        $http({
                            url: '/wechatshop/role/remove_user_role',
                            method: 'POST',
                            headers: formHeaders,
                            data: $.param({
                                userId: userId,
                                roleId: roleId
                            })
                        }).success(ngPromiseHandler(resolve, reject))
                            .error(reject);
                    });
                },
                changePassword: function (password) {
                    return new Promise(function (resolve, reject) {
                        if (!password) {
                            reject('密码不可为空');
                            return;
                        }
                        password = password.trim();
                        $http({
                            url: '/wechatshop/user/change_password',
                            method: 'POST',
                            headers: formHeaders,
                            data: $.param({
                                password: password
                            })
                        }).success(ngPromiseHandler(resolve, reject))
                            .error(reject);
                    })
                },
                listUsers: function (page, pageSize) {
                    page = page || 1;
                    pageSize = pageSize || 10;
                    return new Promise(function (resolve, reject) {
                        $http.get('/wechatshop/user/list?page=' + page + '&page_size=' + pageSize)
                            .success(function (data) {
                                if (data.code === 0) {
                                    resolve(data.data.records, data.data.total);
                                } else {
                                    reject(data.data);
                                }
                            }).error(reject);
                    });
                },
                listWechatPushContents: function (page, pageSize) {
                    page = page || 1;
                    pageSize = pageSize || 10;
                    return new Promise(function (resolve, reject) {
                        $http.get('/wechatshop/user/list_wechat_push_contents?page=' + page + '&page_size=' + pageSize)
                            .success(function (data) {
                                if (data.code === 0) {
                                    resolve(data.data.records, data.data.total);
                                } else {
                                    reject(data.data);
                                }
                            }).error(reject);
                    });
                },
                listWechatPushHistoriesOfContent: function (id) {
                    return new Promise(function (resolve, reject) {
                        $http.get('/wechatshop/user/list_wechat_push_histories/' + id)
                            .success(ngPromiseHandler(resolve, reject)).error(reject);
                    });
                },
                pushWechatPushContent: function (id) {
                    return new Promise(function (resolve, reject) {
                        $http({
                            url: '/wechatshop/push_wechat_group_news/' + id,
                            method: 'POST',
                            headers: formHeaders
                        }).success(ngPromiseHandler(resolve, reject)).error(reject);
                    });
                },
                deleteWechatPushContent: function (id) {
                    return new Promise(function (resolve, reject) {
                        $http({
                            url: '/wechatshop/user/delete_wechat_push_content/' + id,
                            method: 'POST',
                            headers: formHeaders
                        }).success(ngPromiseHandler(resolve, reject)).error(reject);
                    });
                },
                getAllRoles: _.memoize(function () {
                    return new Promise(function (resolve, reject) {
                        $http.get('/wechatshop/role/all')
                            .success(ngPromiseHandler(resolve, reject))
                            .error(reject);
                    });
                }),
                getConfig: function (key) {
                    if (isInWeixin && configPromisesInWechat[key]) {
                        return configPromisesInWechat[key];
                    }
                    var promise = new Promise(function (resolve, reject) {
                        $http.get('/wechatshop/config/' + key)
                            .success(ngPromiseHandler(resolve, reject))
                            .error(reject);
                    });
                    if (isInWeixin) {
                        configPromisesInWechat[key] = promise;
                    }
                    return promise;
                },
                setConfig: function (key, value) {
                    return new Promise(function (resolve, reject) {
                        $http({
                            url: '/wechatshop/set_config',
                            headers: formHeaders,
                            method: 'POST',
                            data: $.param({
                                key: key,
                                value: value
                            })
                        }).success(ngPromiseHandler(resolve, reject))
                            .error(reject);
                    });
                }
            };
            return model;
        }]);